package com.summer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.entity.SetMeal;
import com.summer.entity.SetmealDish;
import com.summer.entity.SetmealDto;
import com.summer.mapper.SetMealMapper;
import com.summer.service.SetMealService;
import com.summer.service.SetmealDishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, SetMeal> implements SetMealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Transactional
    @Override
    public void addSetMealAndSetMealDish(SetmealDto setmealDto) {
        //1. 添加套餐 : 补充套餐字段，调用添加api --无补充值
        this.save(setmealDto);

        //2. 添加套餐与菜品关联表：补充关联表字段，调用api  --setmealId需要补充
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        // 从记录列表中取出每一个记录，添加setmealId
        for (int i = 0; i < setmealDishList.size(); i++) {
            SetmealDish setmealDish = setmealDishList.get(i);
            setmealDish.setSetmealId(setmealDto.getId()); // 因为套餐执行了save语句已自动生成id，故存在id
        }
        setmealDishService.saveBatch(setmealDishList);
        //3. 事务控制 -已加注解
        //4. 异常处理 -套餐名不能重复，已设置重复key异常处理器捕获
    }

    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        //1. 删除套餐表
        this.removeByIds(ids);
        //2. 删除关联表
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.in(SetmealDish::getSetmealId, ids);  // TODO 第二个参数为集合
        setmealDishService.remove(lqw);
        //3. 异常处理 --无
        //4. 事务处理 --已加
    }
}
